package com.century.sjt.activity;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.widget.SwipeRefreshLayout;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.ListView;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.century.sjt.R;
import com.century.sjt.adapter.MerchatOrderAdapter;
import com.century.sjt.entity.MyOrderInfo;
import com.century.sjt.util.Constant;
import com.century.sjt.util.TipUtil;
import com.century.sjt.widget.TitleBar.SjtTitleBar;

import org.json.JSONArray;
import org.json.JSONObject;
import org.json.JSONTokener;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * @author:周玲波
 * @Description: 商家、分店：我的订单
 * @date : 2016/9/5 14:53
 */
public class MerchantOrderActivity extends BaseActivity {
    @BindView(R.id.my_order_title)
    SjtTitleBar title;
    @BindView(R.id.lv_content)
    ListView mListView;
    @BindView(R.id.activity_list_refesh)
    SwipeRefreshLayout mSwipeLayout;
    private int iCurrPage = 1;
    List<MyOrderInfo> mList;
    private Handler mHandler;
    private Boolean isDataChangeOk = true;
    private MerchatOrderAdapter myOrderAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my_order);
        ButterKnife.bind(this);
        initView();
        initEvent();
        initData();
    }

    @Override
    protected void initView() {
        title.setTitle(getResources().getString(R.string.text_order));
        title.setLeftIconResource(getResources().getString(R.string.icon_return));
        title.setLeftLayoutClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        mList = new ArrayList<>();
    }

    @Override
    protected void initEvent() {
            mHandler = new Handler() {
                @Override
                public void handleMessage(Message msg) {
                    switch (msg.what) {
                        case 1:
                            myOrderAdapter.notifyDataSetChanged();
                            TipUtil.closeProgressDialog();
                            mSwipeLayout.setRefreshing(false);
                            break;
                        case 2:
                            isDataChangeOk = true;
                            mList.clear();
                            iCurrPage = 1;
                            initData();
                            break;
                        case 3:
                            if (isDataChangeOk) {
                                mSwipeLayout.setRefreshing(true);
                                iCurrPage++;
                                initData();
                            }
                            break;
                    }
                }
            };
            mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                }
            });
            mListView.setOnScrollListener(new AbsListView.OnScrollListener() {
                @Override
                public void onScrollStateChanged(AbsListView view, int scrollState) {
                    switch (scrollState) {
                        // 当不滚动时
                        case AbsListView.OnScrollListener.SCROLL_STATE_IDLE:
                            // 判断滚动到底部
                            mSwipeLayout.setEnabled(true);
                            if (mListView.getLastVisiblePosition() == (mListView.getCount() - 1)) {
                                //加载更多功能的代码
                                Message msg = new Message();
                                msg.what = 3;
                                mHandler.sendMessage(msg);
                            }
                            break;
                        case AbsListView.OnScrollListener.SCROLL_STATE_FLING:
                            mSwipeLayout.setEnabled(false);
                            break;
                        case AbsListView.OnScrollListener.SCROLL_STATE_TOUCH_SCROLL:
                            mSwipeLayout.setEnabled(false);
                            break;
                    }
                }
                @Override
                public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
                    View firstView = mListView.getChildAt(firstVisibleItem);
                    if (firstVisibleItem == 0 && (firstView == null || firstView.getTop() == 0))
                        mSwipeLayout.setEnabled(true);
                    else
                        mSwipeLayout.setEnabled(false);
                }
            });
            mSwipeLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
                @Override
                public void onRefresh() {
                    Message msg = new Message();
                    msg.what = 2;
                    mHandler.sendMessage(msg);
                }
            });
            mSwipeLayout.setColorSchemeResources(android.R.color.holo_blue_bright, android.R.color.holo_green_light,
                    android.R.color.holo_orange_light, android.R.color.holo_red_light);
    }

    @Override
    protected void initData() {
            isDataChangeOk = false;
            StringRequest stringRequest = new StringRequest(Request.Method.POST, Constant.myOrderInfoListHost, new Response.Listener<String>() {
                @Override
                public void onResponse(String response){
                    try {
                        isDataChangeOk = true;
                        mList.clear();
                        TipUtil.closeProgressDialog();
                        JSONTokener jsonParser = new JSONTokener(response);
                        JSONObject res = (JSONObject) jsonParser.nextValue();
                        String code = res.getString("code");
                        String message = res.getString("message");
                        if (code.equals("200")) {
                            JSONObject data = res.getJSONObject("data");
                            if (data.length()!= Constant.PAGESIZE){
                                isDataChangeOk = false;
                            }
                            JSONArray myOrderListist = data.getJSONArray("myOrderListist");
                            for (int i = 0; i < myOrderListist.length(); i++) {
                                JSONObject aData = (JSONObject) myOrderListist.get(i);
                                MyOrderInfo myOrderInfo = new MyOrderInfo();
                                myOrderInfo.setOrderId(aData.getString("orderId"));
                                myOrderInfo.setStatusName(aData.getString("statusName"));
                                myOrderInfo.setDate(aData.getString("date"));
                                myOrderInfo.setOrderCurrency(aData.getString("orderCurrency"));
                                myOrderInfo.setOrderAmount(aData.getString("orderAmount"));
                                myOrderInfo.setDiscountAmount(aData.getString("discountAmount"));
                                myOrderInfo.setGoodsQuantity(aData.getString("goodsQuantity"));
                                myOrderInfo.setImage(aData.getString("image"));
                                mList.add(myOrderInfo);
                            }
                        } else {
                            TipUtil.showToast(message, MerchantOrderActivity.this, 1);
                        }
                    } catch (Exception ex) {
                        ex.printStackTrace();
                        TipUtil.showToast(getResources().getString(R.string.error_service), MerchantOrderActivity.this, 1);
                    }
                    TipUtil.closeProgressDialog();
                    Message msg = new Message();
                    msg.what = 1;
                    mHandler.sendMessage(msg);
                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    TipUtil.showToast(getResources().getString(R.string.error_network), MerchantOrderActivity.this, 1);
                    TipUtil.closeProgressDialog();
                    isDataChangeOk = true;
                    iCurrPage--;
                    Message msg = new Message();
                    msg.what = 1;
                    mHandler.sendMessage(msg);
                }
            }) {
                @Override
                protected Map<String, String> getParams() throws AuthFailureError {
                    Map<String, String> map = new HashMap<String, String>();
                    SharedPreferences mainSharedPreferences = getSharedPreferences(Constant.TAG, Activity.MODE_PRIVATE);
                    String userId = mainSharedPreferences.getString("userId", "");
                    map.put("loginId", userId);
                    map.put("paging.currentPage", String.valueOf(iCurrPage));//当前页码
                    map.put("paging.pageSize", Constant.PAGESIZE + " ");//查询条数
                    return map;
                }

                @Override
                public Map<String, String> getHeaders() throws AuthFailureError {
                    SharedPreferences mainSharedPreferences = getSharedPreferences(Constant.TAG, Activity.MODE_PRIVATE);
                    String cookie = mainSharedPreferences.getString("cookie", "");
                    String rememberMeValue = mainSharedPreferences.getString("rememberMe", "");
                    HashMap localHashMap = new HashMap();
                    String cookieValue = cookie + ";" + rememberMeValue;
                    localHashMap.put("Cookie", cookieValue);
                    return localHashMap;
                }
            };
            mQueue.add(stringRequest);
            myOrderAdapter=new MerchatOrderAdapter(this,mList);
            mListView.setAdapter(myOrderAdapter);
            mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    Intent intent = new Intent(MerchantOrderActivity.this, MerchantOrderDetailActivity.class);
                    intent.putExtra("orderId", mList.get(position).getOrderId());
                    intent.putExtra("falg",2);
                    startActivity(intent);
                }
            });

    }
}
